//
//  MHCollectionViewController.m
//  MHO
//
//  Created by papo on 3/13/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHCollectionViewController.h"
#import "MHAppDelegate.h"
#import "Lib.h"
#import "Collection.h"
#import "MHCollectionCell.h"
#import "MHAppCollectListViewController.h"

@interface MHCollectionViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray* data;
@property (strong, nonatomic) IBOutlet UIView *createCollectionView;
@property (weak, nonatomic) IBOutlet UITextView *collectionDesText;
@property (weak, nonatomic) IBOutlet UITextField *collectionNameText;
@property (strong, nonatomic) NSMutableArray* listGameCollection;

@end

@implementation MHCollectionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.tableView registerNib:[UINib nibWithNibName:@"MHCollectionCell" bundle:nil] forCellReuseIdentifier:@"CollectionCell"];
    self.createCollectionView.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 3);
    self.createCollectionView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.createCollectionView.layer.borderWidth = 1;
    self.createCollectionView.layer.cornerRadius = 10;
    self.createCollectionView.backgroundColor = [UIColor lightGrayColor];
    self.createCollectionView.layer.masksToBounds = YES;
    [self.view addSubview:self.createCollectionView];
    self.createCollectionView.hidden = YES;
    
    _collectionDesText.layer.borderWidth = 1;
    _collectionDesText.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _collectionDesText.layer.cornerRadius = 10;
    _collectionDesText.layer.masksToBounds = YES;
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:@"MHCollectionCellDelete" object:nil];
    [self registerForKeyboardNotifications];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark UIGestureRecognizerDelegate methods

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    
    if (self.createCollectionView.hidden && [touch.view isDescendantOfView:self.tableView]) {
        
        // Don't let selections of auto-complete entries fire the
        // gesture recognizer
        return NO;
    }
    
    return YES;
}

- (void)tapGesture:(UIGestureRecognizer*)gesture {
    if (_collectionDesText.isFirstResponder) {
        [_collectionDesText resignFirstResponder];
        return ;
    }
    
    if (_collectionNameText.isFirstResponder) {
        [_collectionNameText resignFirstResponder];
        return;
    }
    
    self.createCollectionView.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self refresh];
}

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    CGRect frame = self.createCollectionView.frame;
    float offset = frame.origin.y + frame.size.height + kbSize.height - self.view.frame.size.height;
    if (offset > 0) {
        frame.origin.y -= (offset);
        [UIView animateWithDuration:0.3 animations:^{
            self.createCollectionView.frame = frame;
        }];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [UIView animateWithDuration:0.3 animations:^{
        self.createCollectionView.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 3);
    }];
}

- (void)refresh {
    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/chude?IdSystem=2&User=%@&pageIndex=0&pageSize=20&key=%@", [Lib stringForKey:@"Email"], kServerKey];
    [Lib showLoadingView];
    if (self.listGameCollection == nil) {
        self.listGameCollection = [NSMutableArray array];
    }
    else{
        [self.listGameCollection removeAllObjects];
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.data = [Collection getCollectionFromUrl:url];
        NSString* colUrl = @"http://mobile.mho.vn/services/chude?gameid=0&chudeid=%@&pageIndex=0&pageSize=6&key=%@";
        for (Collection* col in self.data) {
            NSString* cUrl = [NSString stringWithFormat:colUrl, col.colletionId, kServerKey];
            NSArray* array = [Application appsFromServiceUrl:cUrl];
            if (array) {
                [self.listGameCollection addObject:array];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            [self.tableView reloadData];
            _collectionNumLb.text = [NSString stringWithFormat:@"CHỦ ĐỀ CỦA BẠN (%lu)", (unsigned long)self.data.count];
        });
    });
}

- (void)leftButtonPressed:(id)sender {
    [[MHAppDelegate sharedApp].viewController showLeftPanelAnimated:YES];
}

- (IBAction)createNewCollection:(id)sender {
    self.createCollectionView.hidden = NO;
}
- (IBAction)comfirmCreateCollection:(id)sender {
    NSString* name = _collectionNameText.text;
    NSString* des = _collectionDesText.text;
    if (!name || name.length == 0) {
        [UIAlertView showWithTitle:@"Thông báo" message:@"Bạn chưa nhập tên chủ đề!" cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
        }];
        return;
    }
    
//    if (!des || des.length == 0) {
//        [UIAlertView showWithTitle:@"Thông báo" message:@"Bạn chưa nhập trích dẫn!" cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//            
//        }];
//        return;
//    }
    
    Collection* col = [[Collection alloc] init];
    col.collectionName = name;
    col.colletionId = @(0);
    col._description = des;
    col.userEmail = [Lib stringForKey:@"Email"];
    
    
    [Lib showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [Collection createNewCollection:col];
       dispatch_async(dispatch_get_main_queue(), ^{
           [self refresh];
           [self.createCollectionView endEditing:YES];
           [Lib removeLoadingView];
           self.createCollectionView.hidden = YES;
       });
    });
}

#pragma mark - UITableViewSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 98;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MHCollectionCell* cell = [tableView dequeueReusableCellWithIdentifier:@"CollectionCell"];
    if (!cell) {
        cell = [MHCollectionCell cellFromNib];
    }
    
    Collection* col = [self.data objectAtIndex:indexPath.row];
    [cell setCollection:col];
    
    if (indexPath.row < _listGameCollection.count) {
        NSArray* array = self.listGameCollection[indexPath.row];
        [cell setListGame:array];
    }
    
    if (indexPath.row == 0) {
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleDefault];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //http://mobile.mho.vn/services/chude?gameid=1&chudeid=2&pageIndex=0&pageSize=10&key=mho123190456$@!
    Collection* col = [self.data objectAtIndex:indexPath.row];
    
    MHAppCollectListViewController* vc = [[MHAppCollectListViewController alloc] initWithNibName:@"MHAppCollectListViewController" bundle:nil];
    if (col.colletionId.integerValue != 0) {
        [vc setCollection:col];
        [vc setFavorite:NO];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/chude?Id=%@&key=%@", col.colletionId, kServerKey];
            [ServiceLib sendGetRequest:url useCache:NO];
        });
    }
    else {
        // http://mobile.mho.vn/services/LikeGame?GameId=110&IdSystem=1&User=nguyenviethien.1992@gmail.com&pageIndex=0&pageSize=19&key=mho123190456$@!
        [vc setFavorite:YES];
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}


@end
